package java_class_work.week08.internet.chat1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @Author Tiam
 * @Date 2022/10/31 18:21
 * @Description:
 */
public class Send implements Runnable {
    DatagramSocket ds = null;

    @Override
    public void run() {
        sendMessage();
    }

    /**
     * 发送消息
     */
    private void sendMessage() {
        try {
            // 1. 新建服务
            ds = new DatagramSocket();
            // 2. 输入数据
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String message = null;
            System.out.println("tips:请先输入stop停止接收端,再输入over停止发送端输入");
            System.out.print("请输入消息: ");
            while ((message = br.readLine()) != null) {
                if ("over".equalsIgnoreCase(message)) break;
                // 3. 封装数据 和发送地址到 dp
                DatagramPacket dp = new DatagramPacket(message.getBytes(), message.length(), InetAddress.getByName("192.168.60.249"), 6666);
                // 4. 发送数据
                ds.send(dp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭服务
            if (ds != null) ds.close();
        }
    }
}
